package com.gtc.zsk.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gtc.zsk.annotation.AuthCheck;
import com.gtc.zsk.common.BaseResponse;
import com.gtc.zsk.common.DeleteRequest;
import com.gtc.zsk.common.ErrorCode;
import com.gtc.zsk.common.ResultUtils;
import com.gtc.zsk.constant.UserConstant;
import com.gtc.zsk.exception.BusinessException;
import com.gtc.zsk.exception.ThrowUtils;
import com.gtc.zsk.model.dto.questionBankQuestion.QuestionBankQuestionQueryRequest;
import com.gtc.zsk.model.dto.vipBankUser.VipBankUserAddRequest;
import com.gtc.zsk.model.dto.vipBankUser.VipBankUserQueryRequest;
import com.gtc.zsk.model.dto.vipBankUser.VipBankUserRemoveRequest;
import com.gtc.zsk.model.dto.vipBankUser.VipBankUserUpdateRequest;
import com.gtc.zsk.model.entity.QuestionBankQuestion;
import com.gtc.zsk.model.entity.User;
import com.gtc.zsk.model.entity.VipBankUser;
import com.gtc.zsk.model.vo.QuestionBankQuestionVO;
import com.gtc.zsk.model.vo.VipBankUserVO;
import com.gtc.zsk.service.UserService;
import com.gtc.zsk.service.VipBankUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 題库vip用户接口
 *
 * @author <a href="https://github.com/ligtc">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/vipBankUser")
@Slf4j
public class VipBankUserController {

    @Resource
    private VipBankUserService vipBankUserService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建題库vip用户
     *
     * @param vipBankUserAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addVipBankUser(@RequestBody VipBankUserAddRequest vipBankUserAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(vipBankUserAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        VipBankUser vipBankUser = new VipBankUser();
        BeanUtils.copyProperties(vipBankUserAddRequest, vipBankUser);
        // 数据校验
        vipBankUserService.validAndAddVipBankUser(vipBankUser, true);
        // 返回新写入的数据 id
        long newVipBankUserId = vipBankUser.getId();
        return ResultUtils.success(newVipBankUserId);
    }

    /**
     * 删除題库vip用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteVipBankUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        VipBankUser oldVipBankUser = vipBankUserService.getById(id);
        ThrowUtils.throwIf(oldVipBankUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldVipBankUser.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = vipBankUserService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

//    /**
//     * 更新題库vip用户（仅管理员可用）
//     *
//     * @param vipBankUserUpdateRequest
//     * @return
//     */
//    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Boolean> updateVipBankUser(@RequestBody VipBankUserUpdateRequest vipBankUserUpdateRequest) {
//        if (vipBankUserUpdateRequest == null || vipBankUserUpdateRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        // todo 在此处将实体类和 DTO 进行转换
//        VipBankUser vipBankUser = new VipBankUser();
//        BeanUtils.copyProperties(vipBankUserUpdateRequest, vipBankUser);
//        // 数据校验
//        vipBankUserService.validVipBankUser(vipBankUser, false);
//        // 判断是否存在
//        long id = vipBankUserUpdateRequest.getId();
//        VipBankUser oldVipBankUser = vipBankUserService.getById(id);
//        ThrowUtils.throwIf(oldVipBankUser == null, ErrorCode.NOT_FOUND_ERROR);
//        // 操作数据库
//        boolean result = vipBankUserService.updateById(vipBankUser);
//        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
//        return ResultUtils.success(true);
//    }

    /**
     * 根据 id 获取題库vip用户（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<VipBankUserVO> getVipBankUserVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        VipBankUser vipBankUser = vipBankUserService.getById(id);
        ThrowUtils.throwIf(vipBankUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(vipBankUserService.getVipBankUserVO(vipBankUser, request));
    }

    /**
     * 移除vip題库用户关联
     *
     * @param vipBankUserRemoveRequest
     * @return
     */
    @PostMapping("/remove")
    public BaseResponse<Boolean> removeVipBankUser(@RequestBody VipBankUserRemoveRequest vipBankUserRemoveRequest) {
        ThrowUtils.throwIf(vipBankUserRemoveRequest == null, ErrorCode.PARAMS_ERROR);
        Long questionBankId = vipBankUserRemoveRequest.getQuestionBankId();
        Long userId = vipBankUserRemoveRequest.getUserId();
        LambdaQueryWrapper<VipBankUser> lambdaQueryWrapper = Wrappers.lambdaQuery(VipBankUser.class)
                .eq(VipBankUser::getQuestionBankId, questionBankId)
                .eq(VipBankUser::getUserId, userId);
        boolean result = vipBankUserService.removeAndUpdateUserVipLevel(lambdaQueryWrapper, userId);
        return ResultUtils.success(result);
    }

    @PostMapping("/list/page/vo")
    public BaseResponse<Page<VipBankUserVO>> listVipBankUserVOByPage(@RequestBody VipBankUserQueryRequest vipBankUserQueryRequest,
                                                                                       HttpServletRequest request) {
        long current = vipBankUserQueryRequest.getCurrent();
        long size = vipBankUserQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<VipBankUser> vipBankUserPage = vipBankUserService.page(new Page<>(current, size),
                vipBankUserService.getQueryWrapper(vipBankUserQueryRequest));
        // 获取封装类
        return ResultUtils.success(vipBankUserService.getVipBankUserVOPage(vipBankUserPage, request));
    }

//    /**
//     * 分页获取当前登录用户创建的題库vip用户列表
//     *
//     * @param vipBankUserQueryRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/my/list/page/vo")
//    public BaseResponse<Page<VipBankUserVO>> listMyVipBankUserVOByPage(@RequestBody VipBankUserQueryRequest vipBankUserQueryRequest,
//                                                                 HttpServletRequest request) {
//        ThrowUtils.throwIf(vipBankUserQueryRequest == null, ErrorCode.PARAMS_ERROR);
//        // 补充查询条件，只查询当前登录用户的数据
//        User loginUser = userService.getLoginUser(request);
//        vipBankUserQueryRequest.setUserId(loginUser.getId());
//        long current = vipBankUserQueryRequest.getCurrent();
//        long size = vipBankUserQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        // 查询数据库
//        Page<VipBankUser> vipBankUserPage = vipBankUserService.page(new Page<>(current, size),
//                vipBankUserService.getQueryWrapper(vipBankUserQueryRequest));
//        // 获取封装类
//        return ResultUtils.success(vipBankUserService.getVipBankUserVOPage(vipBankUserPage, request));
//    }


    // endregion
}
